<!--https://github.com/auspicious-one/vue-vercode-->
<template>
  <div class="uni-code-input-main">
    <div
      class="uni-code-input-main-item"
      :class="{blink:value.length === index && isFocus}"
      v-for="(item,index) in codeList"
      :key="index"
    >{{value[index] ||''}}</div>
    <input class="uni-code-input-input"
           :value="value"
           @focus="isFocus = true"
           @blur="isFocus = false"
           @input="handleInput"
           :maxlength="codeLength" />
  </div>
</template>

<script>
export default {
  name: 'CodeInput',
  props: {
    codeLength: {
      default: 6,
      type: Number
    },
    value: {
      required: true,
      type: String,
      default: ''
    }
  },
  data () {
    return {
      codeList: [],
      isFocus: false
    }
  },
  mounted () {
    // 定义一个数组用于循环
    this.codeList = new Array(this.codeLength).fill('')
  },
  watch: {
    // // 截取字符长度
    // code() {
    //   if (this.value.length > this.codeLength) {
    //     this.$emit('update:value', this.value.substring(0, this.codeLength))
    //   }
    // }
  },
  methods: {
    getCode () {
      return this.code
    },
    handleInput (e) {
      let val = e.target.value
      if (val.length > this.codeLength) {
        val = val.substring(0, this.codeLength)
      }
      console.log(val)
      this.$emit('input', val)
      this.$emit('change', val)
    }
  }
}
</script>
<style scoped>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}

.uni-code-input-main {
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  position: relative;
}

.uni-code-input-input {
  height: 62px;
  width: 10000px;
  margin-left: -5000px;
  position: absolute;
  border: none;
  outline: none;
  color: transparent;
  background-color: transparent;
  /*background-color: rgba(0,0,0,.5);*/
  text-shadow: 0 0 0 transparent;
}

.uni-code-input-main-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 56px;
  background-color: #fff;
  border-radius: 4px;
  font-size: 30px;
  color: #323232;
}
.blink::before {
  content: "";
  display: block;
  background-color: #E62335;
  width: 2px;
  height: 30px;
  animation: cursor-blinks 1.5s infinite steps(1, start);
}

@keyframes cursor-blinks {
  0% {
    opacity: 1;
    display: block;
  }
  50% {
    opacity: 0;
    display: none;
  }
  100% {
    opacity: 1;
    display: block;
  }
}
</style>
